package com.efounder.fragment.selectionpay;

import android.content.Context;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.efounder.adapter.MallSelectionPayMultiAdapter;
import com.efounder.bean.MallSelectionPayMultipleBean;
import com.efounder.bean.MallSelectionPayOrderBean;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.AppContext;
import com.efounder.utils.MallRequestUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pansoft.mobilemallpay.pays.AliPay;
import com.pansoft.mobilemallpay.pays.OnPayListener;
import com.pansoft.mobilemallpay.pays.PayInter;
import com.pansoft.mobilemallpay.pays.WxPay;
import com.pansoft.openplanet.bean.CartStackItemBean;
import com.efounder.mvp.base.BasePresenterImpl;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.util.TreasureTransferUtils;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.utilcode.util.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.utils.MallRequestUtil.ORDER_SELECT_PAY_URL;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2018/9/17 20:55
 * @desc : 选择支付的Presenter
 * @version: 1.0
 */
public class SelectionPayPresenter extends BasePresenterImpl<SelectionPayView> {



    public SelectionPayPresenter(SelectionPayView view) {
        super(view);
    }

    /**
     * 请求订单详情接口
     *
     * @param userID  手机号
     * @param orderId 订单编号
     */
    public void getOrderDetailsData(String userID, String orderId) {
        view.showProgress(mContext.getString(R.string.dialog_title_progress_hint));
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("orderIds", orderId);
        MallRequestUtil.getRequest(TAG, ORDER_SELECT_PAY_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                if (view != null) {
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    try {
                        MallSelectionPayOrderBean mallSelectionPayOrderBean = gson.fromJson(response, MallSelectionPayOrderBean.class);
                        view.getDataSuccess(mallSelectionPayOrderBean, getDataMultiple(mallSelectionPayOrderBean));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFail(String error) {
                if(view!=null){
                    view.dismissProgress();
                    view.getFGTDataFail();
                }
            }
        });
    }

    /**
     * 选择支付加载列表数据
     *
     * @return 数据
     */
    public List<MallSelectionPayMultipleBean> getDataMultiple(MallSelectionPayOrderBean mallSelectionPayOrderBean) {
        List<MallSelectionPayMultipleBean> mallSelectionPayMultipleBeans = new ArrayList<>();
        for (MallSelectionPayOrderBean.PrePayInfoBean.TokenUseArrayBean tokenUseArrayBean : mallSelectionPayOrderBean.getPrePayInfo().getTokenUseArray()) {
            //现在不支持多个产品一起支付，判断当前支付金额是否和抵扣金额相等
            if(tokenUseArrayBean.getRmbValue() == mallSelectionPayOrderBean.getPrePayInfo().getOrdersTotalPrice()){
                MallSelectionPayMultipleBean.SelectionPay selectionPay = new MallSelectionPayMultipleBean.SelectionPay();
                selectionPay.setPay(true);
                selectionPay.setTitle(tokenUseArrayBean.getTokenTypeName());
                selectionPay.setTokenIcon(tokenUseArrayBean.getTokenIcon());
                selectionPay.setSurplusNum("");
                selectionPay.setRmbValue(tokenUseArrayBean.getRmbValue() + "");
                selectionPay.setTokenAmount(tokenUseArrayBean.getTokenAmount() + "");
                selectionPay.setTokenTypeId(tokenUseArrayBean.getTokenTypeId());
                mallSelectionPayMultipleBeans.add(new MallSelectionPayMultipleBean(MallSelectionPayMultipleBean.PAY_WAY_ITEM
                        , tokenUseArrayBean.getTokenTypeId(), selectionPay));
            }
        }
        mallSelectionPayMultipleBeans.add(new MallSelectionPayMultipleBean(MallSelectionPayMultipleBean.OTHER_RECHARGE_WAY_TEXT
                , new MallSelectionPayMultipleBean.SelectionPay(mContext.getResources().getString(R.string.mall_selection_pay_other_pay), R.mipmap.default_img, false, "0")));
        mallSelectionPayMultipleBeans.add(new MallSelectionPayMultipleBean(MallSelectionPayMultipleBean.OTHER_RECHARGE_WAY_ITEM
                , MallSelectionPayMultipleBean.ALI_PAY, new MallSelectionPayMultipleBean.SelectionPay(mContext.getResources().getString(R.string.mall_selection_pay_ali_pay)
                , R.drawable.alipay, true, "")));
        mallSelectionPayMultipleBeans.add(new MallSelectionPayMultipleBean(MallSelectionPayMultipleBean.OTHER_RECHARGE_WAY_ITEM
                , MallSelectionPayMultipleBean.WX_PAY, new MallSelectionPayMultipleBean.SelectionPay(mContext.getResources().getString(R.string.mall_selection_pay_wx_pay)
                , R.drawable.wxpay, true, "")));
        return mallSelectionPayMultipleBeans;
    }

    /**
     * adapter item中点击事件的逻辑处理
     *
     * @param adapter                   适配器
     * @param selectionPayMultipleBeans 实体类
     * @param position                  点击位置
     */
    public void onAdapterItemClick(BaseQuickAdapter adapter, List<MallSelectionPayMultipleBean> selectionPayMultipleBeans
            , int position) {
        MallSelectionPayMultipleBean selectionPayMultipleBean = selectionPayMultipleBeans.get(position);
        //根据判断显示隐藏check图片
        //当前item是否能支付，可以支付继续向下走
        if (selectionPayMultipleBean.getSelectionPay().isPay()) {
            //循环列表
            for (int i = 0; i < selectionPayMultipleBeans.size(); i++) {
                //选择两个
//                if (i == position) {
//                    if (selectionPayMultipleBean.getSelectionPay().isSelectPayWay()) {
//                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(false);
//                    } else {
//                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(true);
//                    }
//                } else if (adapter.getItemViewType(i) == selectionPayMultipleBean.getItemType()) {
//                    selectionPayMultipleBeans.get(i).getSelectionPay().setSelectPayWay(false);
//                }
//                //  选择一个
                //如果循环到当前点击位置，根据当前的选择状态设置，如果不是全部设置为false
                if (i == position) {
                    if (selectionPayMultipleBean.getSelectionPay().isSelectPayWay()) {
                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(false);
                    } else {
                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(true);
                    }
                } else {
                    selectionPayMultipleBeans.get(i).getSelectionPay().setSelectPayWay(false);
                }

            }
            adapter.notifyDataSetChanged();
        }
    }


    /**
     * 支付订单
     *
     * @param context     selectionPayActivity
     * @param type        支付类型  查看MallSelectionPayMultipleBean
     * @param orderId     订单编号
     * @param orderTitle  订单标题
     * @param orderAmount 订单金额
     */
    public void pay(Context context, String type, String orderId, String orderTitle, String orderAmount) {

        if (orderId == null) {
            ToastUtils.showShort(mContext.getString(R.string.mall_selection_pay_order_hint));
            return;
        }
        HashMap<String, String> orderBeanMap = new HashMap<>();
        //无法直接向wxpayentryactivity传值,如果支付方式是微信的话
        EnvironmentVariable.setProperty("mobile_pay_good_name", orderTitle);
        String description = String.format(ResStringUtil.getString(R.string.mall_order_id_pay_info), orderId);
        EnvironmentVariable.setProperty("mobile_pay_good_description", description);

        //请求订单号
        PayInter pay = null;
        if (MallSelectionPayMultipleBean.WX_PAY.equals(type)) {
            //wx支付
            pay = new WxPay(context);
            EnvironmentVariable.setProperty("mobile_pay_good_price", "¥ " + orderAmount);
        } else if (MallSelectionPayMultipleBean.ALI_PAY.equals(type)) {
            pay = new AliPay(context);
            EnvironmentVariable.setProperty("mobile_pay_good_price", "¥ " + orderAmount);
        } else if (MallSelectionPayMultipleBean.SILVER_PAY.equals(type)) {
//            ToastUtils.showShort("选择了银钻支付");
            return;
        } else if (MallSelectionPayMultipleBean.BLACK_PAY.equals(type)) {
//            ToastUtils.showShort("选择了黑钻钻支付");
            EnvironmentVariable.setProperty("mobile_pay_good_price", "¥ " + orderAmount);
            return;
        } else if (MallSelectionPayMultipleBean.POWER_PAY.equals(type)) {
//            ToastUtils.showShort("选择了能量支付");
            EnvironmentVariable.setProperty("mobile_pay_good_price", "¥ " + orderAmount);
            return;
        } else if (MallSelectionPayMultipleBean.FGT_PAY.equals(type)) {
            EnvironmentVariable.setProperty("mobile_pay_good_price",  orderAmount+"FGT");
            showPassDialog("4", orderAmount, orderId);
            return;
        }
        orderBeanMap.put("paytype", type);
        orderBeanMap.put("userId", EnvironmentVariable.getUserName());
        orderBeanMap.put("orderIds", orderId);
        //监听页面
        if (view != null) {
            view.listenerActivityNotifycation();
        }

        pay.setURLAndParams(MallRequestUtil.START_PAY_URL, orderBeanMap);

        final PayInter finalPay = pay;
        pay.pay(new OnPayListener() {
            @Override
            public void onPaySuccess() {
                if (view != null) {
                    view.paySuccess(finalPay);
                }
            }

            @Override
            public void onPayFailure(String msg, int code) {
                if (view != null) {
                    view.payFailed(finalPay, msg, code);
                }
            }
        });
    }

    /**
     * 从服务器获取能量余额
     */
    public void getBanlancefromServer() {

        HashMap<String, String> map = new HashMap<>();
        map.put("ethAddress", EnvironmentVariable.getProperty("tc_ethAddress", ""));
        TCRequestUtil.postCommonRequest(TAG, "eth/ethGetBalance", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {

                JSONObject jsonObject = null;

                try {
                    jsonObject = new JSONObject(response);
                    if (jsonObject != null && jsonObject.getString("result").equals("success")) {
                        String balance = jsonObject.getString("balance");
                        balance = BalanceUtil.balanceConvert(balance);
                        if (view != null) {
                            view.getBalanceDataSuccess(balance);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {

                ToastUtils.showShort(AppContext.getInstance().getString(R.string.mail_get_data_fail_again));
            }
        });
    }

    /**
     * 获取银钻数量
     */
    public void getSilverData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        TCRequestUtil.getOAuthRequest(TAG, "integral/integralTotal", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optString("result").equals("success")) {
                        String silverData = jsonObject.optString("integralTotal");
                        if (view != null) {
                            view.getSilverDataSuccess(silverData);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFail(String error) {

            }
        });
    }

    @Override
    public void detachView() {
        view.dismissProgress();
        super.detachView();
        EFHttpRequest.cancelRequest(TAG);
        //关闭交易
        TreasureTransferUtils.getInstance().closeTransaction();

    }

    /**
     * 加载各个积分数据抵扣的方法
     * @param selectionPayMultipleBeans
     * @param ordersTotalPrice
     * @param balanceData
     * @param type
     */
    public void loadBalanceData(List<MallSelectionPayMultipleBean> selectionPayMultipleBeans
            , double ordersTotalPrice, String balanceData, String type
            ,MallSelectionPayMultiAdapter mallSelectionPayMultiAdapter) {
        int i = 0;
        int position = -1;
        //循环列表获取对应的积分
        for (MallSelectionPayMultipleBean selectionPayMultipleBean : selectionPayMultipleBeans) {
            i++;
            if (selectionPayMultipleBean.getPayType().equals(type)) {
                position = i;
                String tokenAmount = selectionPayMultipleBean.getSelectionPay().getTokenAmount() + "";
                //判断当前积分数量和商品价格
                if (Double.valueOf(balanceData) >= Double.valueOf(tokenAmount)) {
                    //如果积分大于价格  显示抵扣信息  否则显示余额不足，不能支付
                    String rmbValue;
                    selectionPayMultipleBean.getSelectionPay().setPay(true);
//                    rmbValue = selectionPayMultipleBean.getSelectionPay().getRmbValue() + "";
//                    selectionPayMultipleBean.getSelectionPay().setPayStatusHint(tokenAmount
//                            + mContext.getString(R.string.mall_selection_pay_integral_deduction)
//                            + rmbValue + mContext.getString(R.string.mall_selection_pay_yuan));
                    selectionPayMultipleBean.getSelectionPay().setPayStatusHint(mContext.getString(R.string.mall_selection_pay_integral_hint)
                            +" "+tokenAmount+" "+mContext.getString(R.string.mall_selection_pay_integral_fgt));
                } else {
                    selectionPayMultipleBean.getSelectionPay().setPay(false);
                    selectionPayMultipleBean.getSelectionPay().setPayStatusHint(mContext.getString(R.string.mall_selection_pay_integral_hint)
                            +" "+tokenAmount+" "+mContext.getString(R.string.mall_selection_pay_integral_fgt)+" ("+mContext.getString(R.string.mall_selection_pay_balance_hint)+")");
                }
                //加载积分余额
                if (balanceData.contains(".")) {
                    selectionPayMultipleBean.getSelectionPay().setSurplusNum(balanceData);
                } else {
                    selectionPayMultipleBean.getSelectionPay().setSurplusNum(BalanceUtil.formatPrice(Double.valueOf(balanceData), true, 0));
                }

            }
        }
        //更新当前item
        mallSelectionPayMultiAdapter.notifyDataSetChanged();

    }

    /**
     * 获取fgt余额
     */
    public void loadFgtBalance() {

        HashMap<String, String> map = new HashMap<>();
        map.put("phoneNumber", EnvironmentVariable.getUserName());
        map.put("cardId", "4");
        TCRequestUtil.getCommonRequest(TAG, "mallBanlance/getBalanceListByPhone", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
//                LogUtils.e("loadFgtBalance---->"+response);
                Gson gson = new GsonBuilder().serializeNulls().create();
                CartStackItemBean cartStackItemBean = gson.fromJson(response, CartStackItemBean.class);
                if (cartStackItemBean != null && cartStackItemBean.getResult().equals("success")) {
                    if(view!=null){
                        view.dismissProgress();
                        if(cartStackItemBean.getData().getBalance().equals("")){
                            view.getFGTBalanceDataSuccess("0");
                        }else {
                            view.getFGTBalanceDataSuccess(cartStackItemBean.getData().getBalance());
                        }

                    }
                }
            }


            @Override
            public void onFail(String error) {
                if(view!=null){
                    view.dismissProgress();
                    view.getFGTDataFail();
                }


            }
        });
    }

    /**
     * 使用积分付款
     * @param tokenId 积分代币id， 4是FGT
     */
    private void checkOutWithToken(String tokenId, String amount, String orderIds) {
        view.showProgress(mContext.getString(R.string.mall_checking));
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("tokenType", tokenId);
        map.put("tokenCount", amount);
        map.put("orderIds", orderIds);
        MallRequestUtil.getRequest(TAG, MallRequestUtil.PAY_BY_TOKEN_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String result = jsonObject.optString("result");
                    if(result.equals(MallRequestUtil.SUCCESS)){
                        if (view != null) {
                            view.dismissProgress();
                            view.paySuccess(null);
                        }
                    }else {
                        if (view != null) {
                            view.dismissProgress();
                            view.payFailed(null, jsonObject.optString("msg"), OnPayListener.ERROR);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFail(String error) {
                if (view != null) {
                    view.dismissProgress();
                    view.payFailed(null, error, OnPayListener.ERROR);
                }
            }
        });
    }


    private void showPassDialog(final String tokenId, final String amount, final String orderIds) {
        PassWordAlertDialog dialog = new PassWordAlertDialog(mContext,
                new PassWordAlertDialog.OnEnterClick() {
                    @Override
                    public void passVerifySuccess(String passWord) {
                       checkOutWithToken(tokenId,amount,orderIds);
                    }
                });
        dialog.setCanCancle(true);
        dialog.show();
    }
}
